<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Goods extends Model
{
    /**
     * 定义主键字段
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 定义表名，不含前缀
     *
     * @var string
     */
    protected $table      = 'wd_goods';

    /**
     * 定义拒绝保存的字段
     *
     * @var array
     */
    protected $guarded    = ['id'];

    /**
     * 开启laravel默认的时间记录
     *
     * @var bool
     */
    public $timestamps = true;
    
    /**
     * 追加字段
     *
     * @var array
     */
    protected $appends = ['pics', 'discount', 'share'];
    
    /**
     * 隐藏字段
     *
     * @var array
     */
    protected $hidden = ['pics', 'discount', 'share'];
    /**
     * 获取图片路径为数组
     *
     * @param [type] $value
     * @return void
     */
    public function getPicAttribute( $value )
    {   
        $pic = json_decode( $value, true );
        if ( is_array($pic)) {

             return isset($pic[0]) ? $pic[0] : '';
        }

        return $pic ? $pic : '';
    }

    /**
     * 追加详情页图片
     *
     * @return void
     */
    public function getPicsAttribute()
    {
        return json_decode( $this->attributes['pic'], true )?:[];
    }

    /**
     * 追加折扣率
     *
     * @return void
     */
    public function getDiscountAttribute()
    {   
        return $this->attributes['retail_price'] / $this->attributes['market_price'] * 10;
    }

    /**
     * 追加分享链接
     *
     * @return void
     */
    public function getShareAttribute()
    {
        return '';
    }



    /**
     * 管理规格表
     *
     * @return void
     */
    public function norm()
    {
        return $this->hasMany('App\Models\GoodsNorm', 'goods_id', 'id');
    }

    /**
     * 组装首页商品
     *
     * @return void
     */
    public static function return_goods( $info )
    {
        $data = [];
     
        if ( $info ) {

            $data['total'] = $info['total'];
            $data['per_page'] = $info['per_page'];
            $data['current_page'] = $info['current_page'];
            $data['last_page'] = $info['last_page'];
          
            if ( $info['data'] !== null) {

               $data['goods'] = $info['data'] ;
            }
        }
       
        return $data;
    }
}
